package com.example.xianji.adapter;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.activity.Main_Add_Friend_LianJieActivity;
import com.example.xianji.activity.Main_Choose_DaTingActivity;
import com.example.xianji.activity.Main_ChuangJain_FenLeiActivity;
import com.example.xianji.activity.Main_ChuangJain_ProductActivity;
import com.example.xianji.R;
import com.example.xianji.bean.Service;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class My_Product_Adapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<Service> list;
    private int come_from;
//    private SharedPreferences sp;
//    private Editor ed;


    public My_Product_Adapter(Context mContext, ArrayList<Service> list, int come_from) {
        super();
        this.mContext = mContext;
        this.list = list;
        this.come_from = come_from;
//        sp = mContext.getSharedPreferences("text", mContext.MODE_PRIVATE);
//        ed = sp.edit();
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int arg0) {
        return arg0;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Holder mHolder;

        if (convertView == null) {
            mHolder = new Holder();

            convertView = View.inflate(mContext, R.layout.service_listview_item, null);
            mHolder.service_title = (TextView) convertView.findViewById(R.id.service_title);
            mHolder.service_time = (TextView) convertView.findViewById(R.id.service_time);
            mHolder.text_bianji = (ImageView) convertView.findViewById(R.id.text_bianji);
            mHolder.button_product_delete = (Button) convertView.findViewById(R.id.button_product_delete);
            mHolder.linearlayout_item = (LinearLayout) convertView.findViewById(R.id.linearlayout_item);
            mHolder.product_status = (TextView) convertView.findViewById(R.id.product_status);
            //	mHolder.Relative_text_bianji=(RelativeLayout) convertView.findViewById(R.id.Relative_text_bianji);

            convertView.setTag(mHolder);
        }
        mHolder = (Holder) convertView.getTag();

        mHolder.service_title.setText(list.get(position).getTitle());
        mHolder.button_product_delete.setVisibility(View.VISIBLE);
        if (come_from == Contant.product_come_from_editor) {
            //我发布的产品页面
            mHolder.product_status.setVisibility(View.VISIBLE);
            if (list.get(position).getStatus() == 0) {
                //审核,0待审核，1通过，2，未通过
                mHolder.product_status.setText("待审核");
            } else if (list.get(position).getStatus() == 1) {
                mHolder.product_status.setText("通过");
            } else if (list.get(position).getStatus() == 2) {
                mHolder.product_status.setText("未通过");
            }
        }
        if (come_from == Contant.product_come_from_indefine_fenlei) {
            //来自于自定义分类，时间隐藏，
            mHolder.service_time.setVisibility(View.INVISIBLE);
        } else {
            mHolder.service_time.setVisibility(View.VISIBLE);
            mHolder.service_time.setText(list.get(position).getCreated_at().substring(0, 11));
        }
        if (come_from == Contant.product_come_from_want_buy) {
            mHolder.text_bianji.setVisibility(View.GONE);
        } else {
            mHolder.text_bianji.setVisibility(View.VISIBLE);
        }
        final int a = position;
        if (come_from == Contant.product_come_from_editor) {
            //我发布的产品页面
            mHolder.linearlayout_item.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, Main_Choose_DaTingActivity.class);
                    intent.putExtra("product_id", list.get(a).getId() + "");
                    intent.putExtra("product_come_from", Contant.product_come_from_editor);
                    mContext.startActivity(intent);
                }
            });
        }

        mHolder.text_bianji.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (come_from == Contant.product_come_from_editor) {
                    //编辑页面
                    Intent intent = new Intent(mContext, Main_ChuangJain_ProductActivity.class);
                    intent.putExtra("product_come_from", Contant.product_come_from_editor);
                    intent.putExtra("product_id", list.get(a).getId());
                    mContext.startActivity(intent);
                } else if (come_from == Contant.product_come_from_indefine_fenlei) {
                    //来自自定义分类列表的编辑分类
                    Intent intent = new Intent(mContext, Main_ChuangJain_FenLeiActivity.class);
                    intent.putExtra("fenlei_come_from", Contant.product_come_from_indefine_fenlei);
                    intent.putExtra("cat_id", list.get(a).getId());
                    intent.putExtra("parent_id", list.get(a).getParent());
                    intent.putExtra("fenlei_title", list.get(a).getTitle());
                    intent.putExtra("fenlei_parent_name", list.get(a).getParent_name());
                    mContext.startActivity(intent);
                } else if (come_from == Contant.product_vip_lianjie_editor) {
                    //来自于我添加的友链去编辑
                    Intent intent = new Intent(mContext, Main_Add_Friend_LianJieActivity.class);
                    intent.putExtra("add_friend_lianjie", Contant.product_vip_lianjie_editor);
                    intent.putExtra("friend_lianjie_name", list.get(a).getTitle());//链接名称
                    intent.putExtra("friend_lianjie_url", list.get(a).getUrl());//链接url
                    intent.putExtra("friend_lianjie_description", list.get(a).getDescription());//链接描述
                    intent.putExtra("friend_lianjie_sort", list.get(a).getStatus());//显示顺序
                    intent.putExtra("friend_lianjie_id", list.get(a).getId());//显示顺序
                    mContext.startActivity(intent);
                }
            }
        });
        mHolder.button_product_delete.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (come_from == Contant.product_come_from_editor) {
                    //来自于我发布的产品页面
                    //删除我发布的产品
                    delete_product(a, list.get(a).getId());
                } else if (come_from == Contant.product_come_from_indefine_fenlei) {
                    //来自于我的自定义分类列表
                    //删除我的分类

                    delete_fenlei(a, list.get(a).getId());
                } else if (come_from == Contant.product_vip_lianjie_editor) {
                    //来自于我添加的友链页面
                    delete_my_friend_lianjie(a, list.get(a).getId());
                } else if (come_from == Contant.product_come_from_want_buy) {
                    //来自于我发布的求购页面
                    Log.i("ssss", "sssss");
                    delete_my_want_buy(a, list.get(a).getId());

                }

            }
        });

        return convertView;
    }

    class Holder {
        TextView service_title;
        TextView service_time, product_status;
        ImageView text_bianji;
        Button button_product_delete;
        LinearLayout linearlayout_item;


    }

    /**
     * 删除产品
     *
     * @param position
     * @param id
     */
    public void delete_product(final int position, int id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("product_id", id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.delete_product,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(mContext, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 删除自定义分类
     */
    public void delete_fenlei(final int position, int id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("category_id", id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.delete_my_fenlei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {

                try {
                    Toast.makeText(mContext, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 删除我添加的友链
     */
    public void delete_my_friend_lianjie(final int position, int id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("linkid", id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.delete_friend_lianjie,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(mContext, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        list.remove(position);
                        notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 删除我发布的求购
     */
    public void delete_my_want_buy(final int position, int id) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("wbid", id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.delete_my_want_buy,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(mContext, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {

                        list.remove(position);
                        notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("errorerrorerror", error + "");
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }
}
